#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gmail翻译友好的邮件模板
"""
import sys
import os
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import smtplib

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config.settings import EMAIL_CONFIG

class TranslationFriendlyMailSender:
    """Gmail翻译友好的邮件发送器"""
    
    def __init__(self):
        self.config = EMAIL_CONFIG
    
    def _create_translation_friendly_confirmation_email(self, user_data: dict, confirmation_url: str, rejection_url: str = None) -> str:
        """创建Gmail翻译友好的管理员确认邮件"""
        
        # 使用内联样式，避免外部CSS被移除
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>新预约申请 - 需要管理员确认</title>
        </head>
        <body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f5f5f5;">
            <div style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
                
                <!-- 头部 -->
                <div style="background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: white; padding: 30px; text-align: center;">
                    <h1 style="margin: 0; font-size: 24px; font-weight: bold;">新预约申请</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">需要管理员确认</p>
                </div>
                
                <!-- 用户信息 -->
                <div style="background: #ffffff; border: 1px solid #e9ecef; margin: 20px; border-radius: 8px; overflow: hidden;">
                    <div style="background: #f8f9fa; padding: 15px 20px; border-bottom: 1px solid #e9ecef;">
                        <h3 style="margin: 0; color: #495057; font-size: 18px;">申请信息</h3>
                    </div>
                    <div style="padding: 20px;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500; width: 100px;">称呼:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('anrede', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">姓名:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('first_name', '')} {user_data.get('last_name', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">邮箱:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('email', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">生日:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('birthday', '')}</td>
                            </tr>"""
        
        # 添加电话（如果提供）
        if user_data.get('phone'):
            html_content += f"""
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">电话:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('phone', '')}</td>
                            </tr>"""
        
        html_content += f"""
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">服务:</td>
                                <td style="padding: 8px 0; color: #212529; font-weight: 600;">{user_data.get('service', '')}</td>
                            </tr>"""
        
        # 添加时间范围信息（如果提供）
        if user_data.get('dateRange') and len(user_data.get('dateRange', [])) > 0:
            date_range = user_data.get('dateRange', [])
            start_date = date_range[0]
            end_date = date_range[-1]
            html_content += f"""
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">期望时间:</td>
                                <td style="padding: 8px 0; color: #212529; font-weight: 600;">{start_date} 至 {end_date}</td>
                            </tr>"""
        else:
            html_content += f"""
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">扫描范围:</td>
                                <td style="padding: 8px 0; color: #212529; font-weight: 600;">当月及下月前7天</td>
                            </tr>"""
        
        html_content += f"""
                        </table>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div style="text-align: center; margin: 30px 20px;">
                    <a href="{confirmation_url}" 
                       style="display: inline-block; background: linear-gradient(135deg, #28a745 0%, #20c997 100%); 
                              color: white; padding: 15px 30px; border-radius: 8px; text-decoration: none; 
                              font-weight: bold; font-size: 16px; box-shadow: 0 4px 8px rgba(40,167,69,0.3);
                              margin-right: 15px;">
                        批准申请
                    </a>"""
        
        # 添加拒绝按钮（如果提供了拒绝URL）
        if rejection_url:
            html_content += f"""
                    <a href="{rejection_url}" 
                       style="display: inline-block; background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); 
                              color: white; padding: 15px 30px; border-radius: 8px; text-decoration: none; 
                              font-weight: bold; font-size: 16px; box-shadow: 0 4px 8px rgba(220,53,69,0.3);"
                       onclick="return confirm('确定要拒绝此申请吗？此操作不可撤销。')">
                        拒绝申请
                    </a>"""
        
        html_content += f"""
                </div>
                
                <!-- 重要提醒 -->
                <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; margin: 20px; padding: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #856404; font-size: 16px;">⚠️ 管理员操作说明</h4>
                    <ul style="margin: 0; padding-left: 20px; color: #856404; font-size: 14px; line-height: 1.6;">
                        <li>请点击上方"批准申请"按钮开始为用户处理预约</li>
                        <li>批准后系统将自动开始为用户寻找可用的预约时间段</li>"""
        
        # 根据是否有时间范围添加不同的说明
        if user_data.get('dateRange') and len(user_data.get('dateRange', [])) > 0:
            html_content += f"""
                        <li>系统将在用户指定的时间范围内查找可用时间段</li>
                        <li>只有找到的时间在指定范围内才会触发预约</li>"""
        else:
            html_content += f"""
                        <li>系统将扫描当月及下月前7天的时间段</li>
                        <li>如果当月没有可用时间，会自动扩展到下个月</li>"""
        
        html_content += f"""
                        <li>预约结果将通过邮件通知用户</li>
                        <li>如拒绝申请，系统将发送拒绝通知给用户</li>
                    </ul>
                </div>
                
                <!-- 底部 -->
                <div style="background: #f8f9fa; padding: 20px; text-align: center; color: #6c757d; font-size: 14px;">
                    <p style="margin: 0;">此邮件由系统自动发送，请勿回复</p>
                    <p style="margin: 5px 0 0 0;">杜伊斯堡签证预约系统 © 2024</p>
                </div>
                
            </div>
        </body>
        </html>
        """
        
        return html_content
    
    def send_translation_friendly_confirmation(self, to_addr: str, user_data: dict, confirmation_url: str, rejection_url: str = None) -> bool:
        """发送Gmail翻译友好的确认邮件"""
        try:
            # 创建邮件内容
            html_content = self._create_translation_friendly_confirmation_email(user_data, confirmation_url, rejection_url)
            
            # 创建邮件
            from_format = email.utils.formataddr(
                (self.config['from_name'], self.config['from_addr'])
            )
            
            msg = MIMEMultipart('alternative')
            msg['From'] = from_format
            msg['To'] = Header(to_addr)
            msg['Subject'] = Header(f"新预约申请 - {user_data.get('first_name', '')} {user_data.get('last_name', '')} - 需要管理员确认")
            msg['Date'] = email.utils.formatdate(localtime=True)
            
            # 添加HTML内容
            html_part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            # 发送邮件
            server = smtplib.SMTP_SSL(self.config['smtp_server'])
            server.connect(self.config['smtp_server'], self.config['smtp_port'])
            server.login(self.config['from_addr'], self.config['password'])
            server.sendmail(self.config['from_addr'], to_addr, msg.as_string())
            server.quit()
            
            return True
            
        except Exception as e:
            print(f"Gmail翻译友好邮件发送失败: {e}")
            return False
    
    def _create_rejection_notification_email(self, user_data: dict) -> str:
        """创建拒绝通知邮件"""
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>申请拒绝通知</title>
        </head>
        <body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f5f5f5;">
            <div style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
                
                <!-- 头部 -->
                <div style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); color: white; padding: 30px; text-align: center;">
                    <h1 style="margin: 0; font-size: 24px; font-weight: bold;">申请拒绝通知</h1>
                    <p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">杜伊斯堡签证预约系统</p>
                </div>
                
                <!-- 用户信息 -->
                <div style="background: #ffffff; border: 1px solid #e9ecef; margin: 20px; border-radius: 8px; overflow: hidden;">
                    <div style="background: #f8f9fa; padding: 15px 20px; border-bottom: 1px solid #e9ecef;">
                        <h3 style="margin: 0; color: #495057; font-size: 18px;">申请信息</h3>
                    </div>
                    <div style="padding: 20px;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500; width: 100px;">称呼:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('anrede', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">姓名:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('first_name', '')} {user_data.get('last_name', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">邮箱:</td>
                                <td style="padding: 8px 0; color: #212529;">{user_data.get('email', '')}</td>
                            </tr>
                            <tr>
                                <td style="padding: 8px 0; color: #6c757d; font-weight: 500;">服务:</td>
                                <td style="padding: 8px 0; color: #212529; font-weight: 600;">{user_data.get('service', '')}</td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <!-- 拒绝通知 -->
                <div style="background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; margin: 20px; padding: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #721c24; font-size: 16px;">❌ 申请已被拒绝</h4>
                    <p style="margin: 0; color: #721c24; font-size: 14px; line-height: 1.6;">
                        很抱歉，您的预约申请已被拒绝。系统将停止为您寻找可用的预约时间段。
                    </p>
                </div>
                
                <!-- 重要提醒 -->
                <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; margin: 20px; padding: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #856404; font-size: 16px;">ℹ️ 重要提醒</h4>
                    <ul style="margin: 0; padding-left: 20px; color: #856404; font-size: 14px; line-height: 1.6;">
                        <li>您的申请已被拒绝，系统将不再处理此预约请求</li>
                        <li>如需重新申请，请重新提交预约申请</li>
                        <li>如有疑问，请联系客服获取帮助</li>
                        <li>感谢您使用杜伊斯堡签证预约系统</li>
                    </ul>
                </div>
                
                <!-- 底部 -->
                <div style="background: #f8f9fa; padding: 20px; text-align: center; color: #6c757d; font-size: 14px;">
                    <p style="margin: 0;">此邮件由系统自动发送，请勿回复</p>
                    <p style="margin: 5px 0 0 0;">杜伊斯堡签证预约系统 © 2024</p>
                </div>
                
            </div>
        </body>
        </html>
        """
        
        return html_content
    
    def send_rejection_notification(self, to_addr: str, user_data: dict) -> bool:
        """发送拒绝通知邮件"""
        try:
            # 创建邮件内容
            html_content = self._create_rejection_notification_email(user_data)
            
            # 创建邮件
            from_format = email.utils.formataddr(
                (self.config['from_name'], self.config['from_addr'])
            )
            
            msg = MIMEMultipart('alternative')
            msg['From'] = from_format
            msg['To'] = Header(to_addr)
            msg['Subject'] = Header(f"申请拒绝通知 - {user_data.get('first_name', '')} {user_data.get('last_name', '')}")
            msg['Date'] = email.utils.formatdate(localtime=True)
            
            # 添加HTML内容
            html_part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            # 发送邮件
            server = smtplib.SMTP_SSL(self.config['smtp_server'])
            server.connect(self.config['smtp_server'], self.config['smtp_port'])
            server.login(self.config['from_addr'], self.config['password'])
            server.sendmail(self.config['from_addr'], to_addr, msg.as_string())
            server.quit()
            
            return True
            
        except Exception as e:
            print(f"拒绝通知邮件发送失败: {e}")
            return False

# 测试函数已移除 - 这是业务模块，不需要测试代码
